<script setup>
import {useWebSocket} from "@/utils/websocket.js";
import {useWebRtc} from "@/utils/webrtc.js";
import {Base64} from "js-base64";
import {fetchGetServerStatus} from "@/axios/websocket.js";
import {ElMessage} from "element-plus";
const {peer} = useWebRtc()
const {webSocketInstance:ws} = useWebSocket(`ws://127.0.0.1:8199/websocket/client`,(code,data,message)=>{
  if (code === '200') {
    const { type, sdp, iceCandidate } = data
    if (type === "answer") {
      console.log('answer')
      peer.setRemoteDescription(new RTCSessionDescription({ type, sdp }))
    } else if (type === "answer_ice") {
      console.log('answer_ice')
      peer.addIceCandidate(JSON.parse(iceCandidate))
    }
  }else if (code === '300') {

  }
})

const openRtc = async () => {
  const status = await fetchGetServerStatus()
  if (status) {
    const data = {
      code: "300",
      message: "success",
      data: status
    }
    ws.send(Base64.encode(JSON.stringify(data))); // 向服务端发送消息
  }
  // if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
  //   ElMessage.error('getDisplayMedia is not supported!');
  // } else {
  //   let stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true })
  //   stream.getTracks().forEach(track => {
  //     peer.addTrack(track, stream)
  //   })
  //   // 将媒体轨道添加到轨道集
  //   const offer = await peer.createOffer()
  //   await peer.setLocalDescription(offer)
  //   const data = {
  //     code: "200",
  //     message: "success",
  //     data: offer
  //   }
  //   ws.send(Base64.encode(JSON.stringify(data))); // 向服务端发送消息
  // }
}

peer.onicecandidate = (e) => {
  console.log(e)
  if (e.candidate) {
    console.log("搜集并发送候选人")
    const data = {
      code: "200",
      message: "success",
      data: {type: `offer_ice`, iceCandidate: e.candidate}
    }
    ws.send(Base64.encode(JSON.stringify(data))); // 向服务端发送消息
  } else {
    console.log("候选人收集完成！")
  }
}
const init = async () => {
}

init()
</script>

<template>
  <el-button @click="openRtc">分享桌面</el-button>
</template>

<style scoped>

</style>